<template>
  <view class="min-h-screen bg-gray-50">
    <!-- Header -->
    <view class="bg-gradient-to-r from-indigo-600 to-purple-600 pb-6">
      <view class="flex items-center justify-center px-4 pt-3 pb-3">
        <text class="text-white text-lg font-semibold">数据看板</text>
      </view>

      <!-- Date Display Bar -->
      <view class="px-4 mt-2">
        <view class="bg-white bg-opacity-10 backdrop-filter backdrop-blur-sm rounded-lg p-3">
          <view class="flex items-center justify-between mb-2">
            <text class="text-white text-sm font-medium opacity-90">{{ currentDateText }}</text>
            <view class="w-8 h-8 flex items-center justify-center" @click="toggleDatePicker">
              <text class="fas fa-calendar-alt text-white text-sm opacity-80"></text>
            </view>
          </view>
          <view class="flex space-x-2">
            <view
              v-for="tab in dateRangeTabs"
              :key="tab.value"
              :class="[
                'flex-1 text-center py-1 px-2 rounded text-xs transition-all',
                currentDateRange === tab.value
                  ? 'bg-white text-indigo-600 font-medium'
                  : 'bg-white bg-opacity-20 text-white'
              ]"
              @click="selectDateRange(tab.value)"
            >
              {{ tab.label }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- Scrollable Content -->
    <scroll-view class="h-screen" scroll-y :show-scrollbar="false">
      <view>
        <!-- Today's Overview -->
        <view class="p-4">
          <view class="flex items-center mb-3">
            <view class="w-1 h-4 bg-indigo-600 rounded-full mr-2"></view>
            <text class="font-bold text-gray-800">今日实时数据</text>
          </view>

          <view class="grid grid-cols-2 gap-3">
            <!-- Sales Card -->
            <view class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-xl p-4 text-white">
              <view class="flex items-start justify-between">
                <view class="flex-1">
                  <text class="text-xs opacity-90 block mb-1">销售额</text>
                  <text class="text-xl font-bold">¥{{ dashboardData.sales }}</text>
                </view>
                <text class="fas fa-money-bill-wave text-lg opacity-70"></text>
              </view>
              <view class="flex items-center mt-3">
                <text class="fas fa-arrow-up text-xs mr-1"></text>
                <text class="text-xs">{{ dashboardData.salesTrend }}%</text>
              </view>
            </view>

            <!-- Orders Card -->
            <view class="bg-gradient-to-br from-green-500 to-green-600 rounded-xl p-4 text-white">
              <view class="flex items-start justify-between">
                <view class="flex-1">
                  <text class="text-xs opacity-90 block mb-1">订单数</text>
                  <text class="text-xl font-bold">{{ dashboardData.orders }}</text>
                </view>
                <text class="fas fa-shopping-bag text-lg opacity-70"></text>
              </view>
              <view class="flex items-center mt-3">
                <text class="fas fa-arrow-up text-xs mr-1"></text>
                <text class="text-xs">{{ dashboardData.ordersTrend }}%</text>
              </view>
            </view>

            <!-- Visitors Card -->
            <view class="bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl p-4 text-white">
              <view class="flex items-start justify-between">
                <view class="flex-1">
                  <text class="text-xs opacity-90 block mb-1">访客数</text>
                  <text class="text-xl font-bold">{{ dashboardData.visitors }}</text>
                </view>
                <text class="fas fa-users text-lg opacity-70"></text>
              </view>
              <view class="flex items-center mt-3">
                <text class="fas fa-arrow-up text-xs mr-1"></text>
                <text class="text-xs">{{ dashboardData.visitorsTrend }}%</text>
              </view>
            </view>

            <!-- Conversion Card -->
            <view class="bg-gradient-to-br from-orange-500 to-orange-600 rounded-xl p-4 text-white">
              <view class="flex items-start justify-between">
                <view class="flex-1">
                  <text class="text-xs opacity-90 block mb-1">转化率</text>
                  <text class="text-xl font-bold">{{ dashboardData.conversion }}%</text>
                </view>
                <text class="fas fa-percentage text-lg opacity-70"></text>
              </view>
              <view class="flex items-center mt-3">
                <text class="fas fa-arrow-up text-xs mr-1"></text>
                <text class="text-xs">{{ dashboardData.conversionTrend }}%</text>
              </view>
            </view>
          </view>
        </view>

        <!-- Sales Trend Chart -->
        <view class="p-4">
          <view class="flex items-center justify-between mb-3">
            <view class="flex items-center">
              <view class="w-1 h-4 bg-indigo-600 rounded-full mr-2"></view>
              <text class="font-bold text-gray-800">销售趋势</text>
            </view>
            <view class="flex items-center space-x-2">
              <picker :value="chartTypeIndex" :range="chartTypes" range-key="label" @change="onChartTypeChange">
                <view class="bg-gray-100 rounded px-2 py-1 flex items-center">
                  <text class="text-xs text-gray-700">{{ chartTypes[chartTypeIndex].label }}</text>
                  <text class="fas fa-chevron-down text-xs text-gray-500 ml-1"></text>
                </view>
              </picker>
              <view class="p-1" @click="refreshChart">
                <text :class="['fas fa-sync-alt text-gray-500 text-xs', isRefreshing ? 'animate-spin' : '']"></text>
              </view>
            </view>
          </view>

          <!-- Bar Chart -->
          <view class="chart-container">
            <view class="chart-area">
              <view class="chart-bars">
                <view
                  v-for="(item, index) in chartData"
                  :key="index"
                  class="chart-item"
                >
                  <view
                    class="chart-bar"
                    :class="index === chartData.length - 1 ? 'bar-highlight' : 'bar-normal'"
                    :style="{height: (item.value * 2.8) + 'rpx'}"
                  ></view>
                </view>
              </view>
            </view>
            <view class="chart-labels">
              <text v-for="(item, index) in chartData" :key="index" class="chart-label">
                {{ item.label }}
              </text>
            </view>
          </view>
        </view>

        <!-- Top Products -->
        <view class="p-4">
          <view class="flex items-center justify-between mb-3">
            <view class="flex items-center">
              <view class="w-1 h-4 bg-indigo-600 rounded-full mr-2"></view>
              <text class="font-bold text-gray-800">热销TOP5</text>
            </view>
            <view class="flex items-center" @click="viewAllProducts">
              <text class="text-xs text-indigo-600">查看全部</text>
              <text class="fas fa-chevron-right text-xs text-indigo-600 ml-1"></text>
            </view>
          </view>

          <view class="space-y-3">
            <view v-for="(product, index) in topProducts" :key="index"
                  class="flex items-center bg-white rounded-lg border border-gray-200 p-3">
              <!-- Rank Badge -->
              <view :class="[
                'w-8 h-8 rounded-full flex items-center justify-center text-sm font-bold text-white mr-3',
                index === 0 ? 'bg-gradient-to-br from-yellow-400 to-orange-400' :
                index === 1 ? 'bg-gradient-to-br from-gray-400 to-gray-500' :
                index === 2 ? 'bg-gradient-to-br from-orange-400 to-orange-500' :
                'bg-gradient-to-br from-gray-300 to-gray-400'
              ]">
                {{ index + 1 }}
              </view>

              <!-- Product Image -->
              <image
                :src="product.image"
                class="w-10 h-10 rounded-lg object-cover mr-3"
                mode="aspectFill"
              ></image>

              <!-- Product Info -->
              <view class="flex-1">
                <text class="text-sm font-medium text-gray-800 block">{{ product.name }}</text>
                <text class="text-xs text-gray-500">销量: {{ product.sales }}件</text>
              </view>

              <!-- Price -->
              <text class="text-sm font-bold text-indigo-600">¥{{ product.price }}</text>
            </view>
          </view>
        </view>

        <!-- Traffic Sources -->
        <view class="p-4">
          <view class="flex items-center mb-3">
            <view class="w-1 h-4 bg-indigo-600 rounded-full mr-2"></view>
            <text class="font-bold text-gray-800">流量来源</text>
          </view>

          <view class="space-y-2">
            <view v-for="source in trafficSources" :key="source.name" class="bg-gray-50 rounded-lg p-3">
              <view class="flex justify-between items-center mb-2">
                <text class="text-sm font-medium text-gray-700">{{ source.name }}</text>
                <text class="text-sm font-bold" :style="{color: source.color}">{{ source.value }}%</text>
              </view>
              <view class="bg-gray-200 rounded-full h-2 overflow-hidden">
                <view
                  class="h-full rounded-full transition-all duration-500"
                  :style="{
                    width: source.value + '%',
                    background: `linear-gradient(to right, ${source.color}, ${source.gradientEnd})`
                  }"
                ></view>
              </view>
            </view>
          </view>
        </view>

        <!-- User Analysis -->
        <view class="p-4">
          <view class="flex items-center mb-3">
            <view class="w-1 h-4 bg-indigo-600 rounded-full mr-2"></view>
            <text class="font-bold text-gray-800">用户分析</text>
          </view>

          <view class="grid grid-cols-2 gap-3">
            <view v-for="metric in userMetrics" :key="metric.name"
                  class="rounded-lg p-3 border"
                  :style="{background: metric.bgColor, borderColor: metric.borderColor}">
              <text class="text-xs text-gray-600 block mb-1">{{ metric.name }}</text>
              <text class="text-xl font-bold block mb-1" :style="{color: metric.color}">{{ metric.value }}</text>
              <view class="flex items-center">
                <text :class="[
                  'fas text-xs mr-1',
                  metric.trend > 0 ? 'fa-arrow-up text-green-600' : 'fa-arrow-down text-red-600'
                ]"></text>
                <text :class="metric.trend > 0 ? 'text-green-600' : 'text-red-600'" class="text-xs">
                  {{ Math.abs(metric.trend) }}%
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- Date Picker Modal -->
    <view v-if="showDatePicker" class="fixed inset-0 bg-black bg-opacity-60 z-50 flex items-end" @click="closeDatePicker">
      <view class="w-full bg-white rounded-t-3xl shadow-2xl animate-fadeInUp" @click.stop>
        <!-- Modal Header -->
        <view class="px-6 pt-6 pb-4 border-b border-gray-100">
          <view class="flex items-center justify-between">
            <view>
              <text class="text-xl font-bold text-gray-900">选择日期范围</text>
              <text class="text-xs text-gray-500 block mt-1">选择您想查看的数据时间段</text>
            </view>
            <view @click="closeDatePicker" class="w-10 h-10 flex items-center justify-center bg-gray-100 rounded-full">
              <text class="fas fa-times text-gray-600 text-lg"></text>
            </view>
          </view>
        </view>

        <view class="px-6 py-5">
          <!-- Quick Select Options -->
          <view class="mb-5">
            <text class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-3 block">快速选择</text>
            <view class="grid grid-cols-4 gap-2">
              <view
                v-for="option in quickDateOptions"
                :key="option.value"
                class="relative"
              >
                <button
                  :class="[
                    'w-full py-3 px-2 rounded-xl text-sm font-medium transition-all duration-200',
                    selectedQuickOption === option.value
                      ? 'bg-gradient-to-r from-indigo-500 to-purple-500 text-white shadow-lg transform scale-105'
                      : 'bg-gray-50 text-gray-700 border border-gray-200 hover:bg-gray-100'
                  ]"
                  @click="selectQuickDate(option.value)"
                >
                  <text class="fas fa-clock text-xs block mb-1" v-if="option.icon"></text>
                  {{ option.label }}
                </button>
                <view v-if="selectedQuickOption === option.value"
                      class="absolute -top-1 -right-1 w-3 h-3 bg-green-500 rounded-full border-2 border-white"></view>
              </view>
            </view>
          </view>

          <!-- Custom Date Range -->
          <view class="mb-6">
            <text class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-3 block">自定义日期</text>
            <view class="grid grid-cols-2 gap-4">
              <view>
                <text class="block text-sm font-medium text-gray-700 mb-2">
                  <text class="fas fa-calendar-minus text-xs mr-1 text-indigo-500"></text>
                  开始日期
                </text>
                <picker mode="date" :value="startDate" @change="onStartDateChange">
                  <view class="w-full px-4 py-3 bg-gray-50 border-2 border-gray-200 rounded-xl flex items-center justify-between transition-all hover:border-indigo-300 focus:border-indigo-500">
                    <text :class="['text-sm', startDate ? 'text-gray-900 font-medium' : 'text-gray-400']">
                      {{ startDate || '请选择' }}
                    </text>
                    <text class="fas fa-chevron-down text-gray-400 text-xs"></text>
                  </view>
                </picker>
              </view>

              <view>
                <text class="block text-sm font-medium text-gray-700 mb-2">
                  <text class="fas fa-calendar-plus text-xs mr-1 text-purple-500"></text>
                  结束日期
                </text>
                <picker mode="date" :value="endDate" @change="onEndDateChange">
                  <view class="w-full px-4 py-3 bg-gray-50 border-2 border-gray-200 rounded-xl flex items-center justify-between transition-all hover:border-purple-300 focus:border-purple-500">
                    <text :class="['text-sm', endDate ? 'text-gray-900 font-medium' : 'text-gray-400']">
                      {{ endDate || '请选择' }}
                    </text>
                    <text class="fas fa-chevron-down text-gray-400 text-xs"></text>
                  </view>
                </picker>
              </view>
            </view>

            <!-- Date Preview -->
            <view v-if="startDate && endDate" class="mt-4 p-3 bg-indigo-50 rounded-xl border border-indigo-200">
              <view class="flex items-center justify-between">
                <text class="text-xs text-indigo-600 font-medium">
                  <text class="fas fa-info-circle text-xs mr-1"></text>
                  选择的时间段
                </text>
                <text class="text-sm font-bold text-indigo-700">
                  {{ calculateDateDiff() }} 天
                </text>
              </view>
            </view>
          </view>

          <!-- Preset Ranges -->
          <view class="mb-6">
            <text class="text-xs font-semibold text-gray-600 uppercase tracking-wider mb-3 block">常用时间段</text>
            <view class="flex flex-wrap gap-2">
              <button
                v-for="preset in presetRanges"
                :key="preset.value"
                :class="[
                  'px-4 py-2 rounded-full text-xs font-medium transition-all',
                  selectedPreset === preset.value
                    ? 'bg-indigo-100 text-indigo-700 border-2 border-indigo-300'
                    : 'bg-white text-gray-600 border border-gray-300 hover:bg-gray-50'
                ]"
                @click="selectPresetRange(preset.value)"
              >
                <text :class="['fas', preset.icon, 'text-xs mr-1']"></text>
                {{ preset.label }}
              </button>
            </view>
          </view>

          <!-- Action Buttons -->
          <view class="flex space-x-3">
            <button
              class="flex-1 bg-gray-100 text-gray-700 py-4 rounded-2xl font-semibold transition-all hover:bg-gray-200 active:scale-95"
              @click="closeDatePicker"
            >
              <text class="fas fa-times text-sm mr-2"></text>
              取消
            </button>
            <button
              class="flex-1 bg-gradient-to-r from-indigo-600 to-purple-600 text-white py-4 rounded-2xl font-semibold shadow-lg transition-all hover:shadow-xl active:scale-95"
              @click="applyDateRange"
            >
              <text class="fas fa-check text-sm mr-2"></text>
              确定应用
            </button>
          </view>
        </view>

        <!-- Safe area for iOS -->
        <view class="h-8 safe-bottom"></view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentDateRange: 'week',
      currentDateText: '',
      showDatePicker: false,
      startDate: '',
      endDate: '',
      chartTypeIndex: 0,
      isRefreshing: false,

      dateRangeTabs: [
        { label: '今日', value: 'today' },
        { label: '近7天', value: 'week' },
        { label: '本月', value: 'month' },
        { label: '本季', value: 'quarter' }
      ],

      dashboardData: {
        sales: '28,586',
        salesTrend: 12.5,
        orders: 186,
        ordersTrend: 8.3,
        visitors: '1,258',
        visitorsTrend: 15.6,
        conversion: 14.8,
        conversionTrend: 2.1
      },

      chartTypes: [
        { label: '销售额', value: 'sales' },
        { label: '订单数', value: 'orders' },
        { label: '访客数', value: 'visitors' },
        { label: '转化率', value: 'conversion' }
      ],

      chartData: [
        { label: '一', value: 60 },
        { label: '二', value: 80 },
        { label: '三', value: 45 },
        { label: '四', value: 90 },
        { label: '五', value: 100 },
        { label: '六', value: 70 },
        { label: '日', value: 85 }
      ],

      topProducts: [
        {
          name: '无线蓝牙耳机',
          sales: 86,
          price: 299,
          image: 'https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=100&h=100&fit=crop'
        },
        {
          name: '智能手表',
          sales: 52,
          price: 1299,
          image: 'https://images.unsplash.com/photo-1523275335684-37898b6baf30?w=100&h=100&fit=crop'
        },
        {
          name: '便携充电宝',
          sales: 41,
          price: 89,
          image: 'https://images.unsplash.com/photo-1609091839311-d5365f9ff1c5?w=100&h=100&fit=crop'
        },
        {
          name: '手机支架',
          sales: 38,
          price: 29,
          image: 'https://images.unsplash.com/photo-1594736797933-d0501ba2fe65?w=100&h=100&fit=crop'
        },
        {
          name: '数据线',
          sales: 35,
          price: 19,
          image: 'https://images.unsplash.com/photo-1591488320449-011701bb6704?w=100&h=100&fit=crop'
        }
      ],

      trafficSources: [
        { name: '搜索流量', value: 42, color: '#5c6bc0', gradientEnd: '#7e57c2' },
        { name: '推荐流量', value: 28, color: '#10b981', gradientEnd: '#34d399' },
        { name: '直接访问', value: 18, color: '#3b82f6', gradientEnd: '#60a5fa' },
        { name: '活动流量', value: 12, color: '#f97316', gradientEnd: '#fb923c' }
      ],

      userMetrics: [
        {
          name: '复购率',
          value: '32.5%',
          trend: 3.2,
          color: '#5c6bc0',
          bgColor: 'linear-gradient(135deg, #f0f4ff, #e8e5ff)',
          borderColor: '#c7d2fe'
        },
        {
          name: '客单价',
          value: '¥153.7',
          trend: 5.8,
          color: '#10b981',
          bgColor: 'linear-gradient(135deg, #f0fdf4, #dcfce7)',
          borderColor: '#bbf7d0'
        },
        {
          name: '新客占比',
          value: '45.2%',
          trend: -2.1,
          color: '#a855f7',
          bgColor: 'linear-gradient(135deg, #faf5ff, #f3e8ff)',
          borderColor: '#e9d5ff'
        },
        {
          name: '会员占比',
          value: '68.3%',
          trend: 7.2,
          color: '#f97316',
          bgColor: 'linear-gradient(135deg, #fff7ed, #fed7aa)',
          borderColor: '#fed7aa'
        }
      ],

      quickDateOptions: [
        { label: '昨天', value: 'yesterday', icon: true },
        { label: '近3天', value: 'last3days', icon: true },
        { label: '上周', value: 'lastweek', icon: true },
        { label: '上月', value: 'lastmonth', icon: true }
      ],

      presetRanges: [
        { label: '本周', value: 'thisweek', icon: 'fa-calendar-week' },
        { label: '本月', value: 'thismonth', icon: 'fa-calendar-days' },
        { label: '本季度', value: 'thisquarter', icon: 'fa-calendar-check' },
        { label: '本年', value: 'thisyear', icon: 'fa-calendar' },
        { label: '过去30天', value: 'last30days', icon: 'fa-history' },
        { label: '过去90天', value: 'last90days', icon: 'fa-clock-rotate-left' }
      ],

      selectedQuickOption: null,
      selectedPreset: null
    }
  },

  onLoad() {
    this.initData()
  },

  onShow() {
    // 页面显示时刷新数据
    this.loadDashboardData(this.currentDateRange)
  },

  methods: {
    initData() {
      this.selectDateRange('week')
      this.updateChartData()
    },


    toggleDatePicker() {
      this.showDatePicker = true
      // 设置默认日期
      if (!this.startDate) {
        const today = new Date()
        const weekAgo = new Date(today.getTime() - 6 * 24 * 60 * 60 * 1000)
        this.endDate = this.formatDateString(today)
        this.startDate = this.formatDateString(weekAgo)
      }
    },

    closeDatePicker() {
      this.showDatePicker = false
    },

    selectDateRange(range) {
      this.currentDateRange = range
      this.updateDateDisplay(range)
      this.loadDashboardData(range)
    },

    updateDateDisplay(range) {
      const today = new Date()
      let dateText = ''

      switch(range) {
        case 'today':
          dateText = this.formatDate(today)
          break
        case 'week':
          const weekStart = new Date(today.getTime() - 6 * 24 * 60 * 60 * 1000)
          dateText = `${this.formatDate(weekStart)} - ${this.formatDate(today)}`
          break
        case 'month':
          dateText = `${today.getFullYear()}年${today.getMonth() + 1}月`
          break
        case 'quarter':
          const quarter = Math.floor(today.getMonth() / 3) + 1
          dateText = `${today.getFullYear()}年第${quarter}季度`
          break
      }

      this.currentDateText = dateText
    },

    formatDate(date) {
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    },

    formatDateString(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },

    loadDashboardData(range) {
      // 模拟根据日期范围加载数据
      const dataSets = {
        today: {
          sales: '8,580',
          orders: 86,
          visitors: '1,258',
          conversion: 14.8
        },
        week: {
          sales: '28,586',
          orders: 186,
          visitors: '8,256',
          conversion: 13.1
        },
        month: {
          sales: '186,240',
          orders: 2865,
          visitors: '25,680',
          conversion: 14.2
        },
        quarter: {
          sales: '856,420',
          orders: 12756,
          visitors: '86,240',
          conversion: 13.8
        }
      }

      const data = dataSets[range] || dataSets.week
      this.dashboardData.sales = data.sales
      this.dashboardData.orders = data.orders
      this.dashboardData.visitors = data.visitors
      this.dashboardData.conversion = data.conversion

      // 更新图表数据
      this.updateChartData()
    },

    onChartTypeChange(e) {
      this.chartTypeIndex = e.detail.value
      this.updateChartData()
    },

    updateChartData() {
      // 模拟不同类型的图表数据
      const chartDataSets = {
        sales: [
          { label: '一', value: 60 },
          { label: '二', value: 80 },
          { label: '三', value: 45 },
          { label: '四', value: 90 },
          { label: '五', value: 100 },
          { label: '六', value: 70 },
          { label: '日', value: 85 }
        ],
        orders: [
          { label: '一', value: 75 },
          { label: '二', value: 65 },
          { label: '三', value: 85 },
          { label: '四', value: 70 },
          { label: '五', value: 95 },
          { label: '六', value: 80 },
          { label: '日', value: 75 }
        ],
        visitors: [
          { label: '一', value: 55 },
          { label: '二', value: 75 },
          { label: '三', value: 65 },
          { label: '四', value: 85 },
          { label: '五', value: 90 },
          { label: '六', value: 75 },
          { label: '日', value: 80 }
        ],
        conversion: [
          { label: '一', value: 40 },
          { label: '二', value: 60 },
          { label: '三', value: 50 },
          { label: '四', value: 75 },
          { label: '五', value: 65 },
          { label: '六', value: 55 },
          { label: '日', value: 70 }
        ]
      }

      const type = this.chartTypes[this.chartTypeIndex].value
      this.chartData = chartDataSets[type] || chartDataSets.sales
    },

    refreshChart() {
      this.isRefreshing = true
      setTimeout(() => {
        this.updateChartData()
        this.isRefreshing = false
        uni.showToast({
          title: '数据已更新',
          icon: 'success',
          duration: 1500
        })
      }, 1000)
    },

    viewAllProducts() {
      uni.navigateTo({
        url: '/pages/products/bestsellers'
      })
    },

    onStartDateChange(e) {
      this.startDate = e.detail.value
    },

    onEndDateChange(e) {
      this.endDate = e.detail.value
    },

    selectQuickDate(period) {
      this.selectedQuickOption = period
      this.selectedPreset = null
      const today = new Date()
      let startDate, endDate

      switch(period) {
        case 'yesterday':
          startDate = new Date(today.getTime() - 24 * 60 * 60 * 1000)
          endDate = startDate
          break
        case 'last3days':
          startDate = new Date(today.getTime() - 3 * 24 * 60 * 60 * 1000)
          endDate = today
          break
        case 'lastweek':
          startDate = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
          endDate = new Date(today.getTime() - 1 * 24 * 60 * 60 * 1000)
          break
        case 'lastmonth':
          startDate = new Date(today.getFullYear(), today.getMonth() - 1, 1)
          endDate = new Date(today.getFullYear(), today.getMonth(), 0)
          break
        default:
          return
      }

      this.startDate = this.formatDateString(startDate)
      this.endDate = this.formatDateString(endDate)
    },

    selectPresetRange(preset) {
      this.selectedPreset = preset
      this.selectedQuickOption = null
      const today = new Date()
      let startDate, endDate

      switch(preset) {
        case 'thisweek':
          const currentDay = today.getDay()
          const diff = today.getDate() - currentDay + (currentDay === 0 ? -6 : 1)
          startDate = new Date(today.setDate(diff))
          endDate = new Date()
          break
        case 'thismonth':
          startDate = new Date(today.getFullYear(), today.getMonth(), 1)
          endDate = new Date()
          break
        case 'thisquarter':
          const quarter = Math.floor(today.getMonth() / 3)
          startDate = new Date(today.getFullYear(), quarter * 3, 1)
          endDate = new Date()
          break
        case 'thisyear':
          startDate = new Date(today.getFullYear(), 0, 1)
          endDate = new Date()
          break
        case 'last30days':
          startDate = new Date(today.getTime() - 30 * 24 * 60 * 60 * 1000)
          endDate = new Date()
          break
        case 'last90days':
          startDate = new Date(today.getTime() - 90 * 24 * 60 * 60 * 1000)
          endDate = new Date()
          break
      }

      this.startDate = this.formatDateString(startDate)
      this.endDate = this.formatDateString(endDate)
    },

    calculateDateDiff() {
      if (!this.startDate || !this.endDate) return 0
      const start = new Date(this.startDate)
      const end = new Date(this.endDate)
      const diffTime = Math.abs(end - start)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1
      return diffDays
    },

    applyDateRange() {
      if (!this.startDate || !this.endDate) {
        uni.showToast({
          title: '请选择日期范围',
          icon: 'none'
        })
        return
      }

      if (new Date(this.startDate) > new Date(this.endDate)) {
        uni.showToast({
          title: '开始日期不能大于结束日期',
          icon: 'none'
        })
        return
      }

      // 更新显示
      const start = new Date(this.startDate)
      const end = new Date(this.endDate)
      this.currentDateText = `${this.formatDate(start)} - ${this.formatDate(end)}`

      // 重置选中状态
      this.currentDateRange = 'custom'

      // 加载数据
      this.loadDashboardData('custom')

      // 关闭弹窗
      this.closeDatePicker()

      uni.showToast({
        title: '日期已更新',
        icon: 'success',
        duration: 1500
      })
    }
  }
}
</script>

<style scoped>
/* Chart container styles */
.chart-container {
  background-color: #f9fafb;
  border-radius: 24rpx;
  padding: 32rpx;
}

.chart-area {
  position: relative;
  height: 300rpx;
  margin-bottom: 20rpx;
}

.chart-bars {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  padding: 0 8rpx;
}

.chart-item {
  flex: 1;
  margin: 0 8rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
}

.chart-bar {
  width: 100%;
  border-radius: 8rpx 8rpx 0 0;
  transition: all 0.3s ease;
  min-height: 30rpx;
}

.bar-normal {
  background: linear-gradient(to top, #5c6bc0, #7986cb);
}

.bar-highlight {
  background: linear-gradient(to top, #7e57c2, #ab47bc);
}

.chart-labels {
  display: flex;
  justify-content: space-between;
  margin-top: 16rpx;
  padding: 0 16rpx;
}

.chart-label {
  flex: 1;
  text-align: center;
  font-size: 24rpx;
  color: #6b7280;
}

.chart-bar:hover {
  transform: scaleY(1.05);
  transform-origin: bottom;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}

/* Date picker modal animation */
@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(100%);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.animate-fadeInUp {
  animation: fadeInUp 0.3s ease-out;
}

/* Button press effect */
.active\:scale-95:active {
  transform: scale(0.95);
}

/* Hover effects */
.hover\:bg-gray-100:hover {
  background-color: #f3f4f6;
}

.hover\:bg-gray-200:hover {
  background-color: #e5e7eb;
}

.hover\:bg-gray-50:hover {
  background-color: #f9fafb;
}

.hover\:shadow-xl:hover {
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

.hover\:border-indigo-300:hover {
  border-color: #a5b4fc;
}

.hover\:border-purple-300:hover {
  border-color: #d8b4fe;
}

/* Transform scale */
.transform {
  transform: translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
}

.scale-105 {
  --tw-scale-x: 1.05;
  --tw-scale-y: 1.05;
}

/* Fix for iOS safe area */
.safe-top {
  padding-top: constant(safe-area-inset-top);
  padding-top: env(safe-area-inset-top);
}

.safe-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}

/* Custom scrollbar styles */
::-webkit-scrollbar {
  width: 0;
  height: 0;
}

/* Ensure FontAwesome icons display correctly */
.fas {
  font-family: 'Font Awesome 6 Free';
  font-weight: 900;
}

.far {
  font-family: 'Font Awesome 6 Free';
  font-weight: 400;
}
</style>